//
//  MapViewController.swift
//  HHSwift
//
//  Created by 华宏 on 2020/9/2.
//  Copyright © 2020 huahong. All rights reserved.
//

import UIKit
import MapKit
import CoreLocation
class MapViewController: BaseViewController {

    var mapView = MKMapView()
    var locationManager = CLLocationManager()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "地图"
        
        self.view.addSubview(self.mapView)
        self.mapView.frame = self.view.bounds
        self.mapView.delegate = self
        self.mapView.mapType = .standard
        self.mapView.showsTraffic = true
        self.mapView.showsCompass = true
        self.mapView.showsCompass = true
        self.mapView.showsPointsOfInterest = true
        
        //开启地图的showsUserLocation属性，并设置方法setUserTrackMode:即可实现跟踪用户的位置和方向变化
        self.mapView.showsUserLocation = true
        self.mapView.userTrackingMode = .follow
        
        //经纬度跨度
        let latitudeDelta:  CLLocationDegrees = 0.007
        let longitudeDelta: CLLocationDegrees = 0.007
        
        let region = MKCoordinateRegion(center: self.mapView.userLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta))
         self.mapView.setRegion(region, animated: true)
                
      
        startLocation()
    }
    

    func startLocation() {
        
        if CLLocationManager.locationServicesEnabled() == false {
            return
        }
        
        if CLLocationManager.authorizationStatus() == .notDetermined {

            self.locationManager.requestWhenInUseAuthorization()
            
        }else if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways {
            
            //一次性的请求当前位置
//            self.locationManager.requestLocation()
            self.locationManager.delegate = self
            self.locationManager.startUpdatingLocation()
        }
    }

    
//MARK: - 跳到系统导航
    func gotoSystemMap(address:String) {
        
        let geoCoder = CLGeocoder.init()
        geoCoder.geocodeAddressString(address) { (placemarks:[CLPlacemark]?, error:Error?) in

           if let _ = error {
              return
            }
            
            guard let newPlacemarks = placemarks else {
               print("placemarks is nil")
               return
            }
            
                
            let placemark = newPlacemarks.last
            let mkPlaceMark = MKPlacemark(placemark: placemark!)
            let sourceItem = MKMapItem.forCurrentLocation()
            let destiItem = MKMapItem.init(placemark: mkPlaceMark)
            
            let options:[String:Any] =
                        [
                           MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit,
                           MKLaunchOptionsMapTypeKey:MKMapType.standard,
                           MKLaunchOptionsShowsTrafficKey:true
                        ]
                          
            
            MKMapItem.openMaps(with: [sourceItem,destiItem], launchOptions: options)
                   
            }
                     
    }
    
//MARK: - 绘制路线
    func drawLine(address:String) {
        
        let geoCoder = CLGeocoder.init()
           geoCoder.geocodeAddressString(address) { (placemarks:[CLPlacemark]?, error:Error?) in

              if let _ = error {
                 return
               }
               
               guard let newPlacemarks = placemarks else {
                  print("placemarks is nil")
                  return
               }
               
                   
               let placemark = newPlacemarks.last
               let mkPlaceMark = MKPlacemark(placemark: placemark!)
               let sourceItem = MKMapItem.forCurrentLocation()
               let destiItem = MKMapItem.init(placemark: mkPlaceMark)
               
              //实现画线
              //1.创建方向请求对象
            let request = MKDirections.Request()
            request.source = sourceItem
            request.destination = destiItem
            let directions = MKDirections(request: request)
            
            //计算两点之间的路线
            directions.calculate { (response:MKDirections.Response?, error:Error?) in
                
                if response == nil || error != nil {
                    
                    return
                }
                
                
                //获取路线信息
                for route  in response!.routes {
                    //折线
                    let polyLine = route.polyline
                    self.mapView.addOverlay(polyLine)
                    
                }
            }
                                  
        }
    }
    
    
    override func topRightAction() {
        
//        drawLine(address: "滕州市")
        gotoSystemMap(address: "滕州市")
    }
}

extension MapViewController:MKMapViewDelegate,CLLocationManagerDelegate {
   
    //MARK: - MKMapViewDelegate
    
    func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
        
    }
    
    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
      
        self.mapView.centerCoordinate = userLocation.coordinate
        
    }
    
    //设置地图渲染物
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        
        let polyLine = MKPolylineRenderer(overlay: overlay)
        polyLine.strokeColor = .red
        polyLine.lineWidth = 3.0
        
        return polyLine
        
    }
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
      
        if annotation is MKUserLocation {
            return nil
        }
        
        let identifier = "annotation"
        var annoView:MKPinAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
        
//        guard let newAnnoView = annoView else {
//          newAnnoView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
//        }
        
//        if let annoView = annoView {
//
//        }else{
//           annoView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
//        }
        
        if annoView == nil {
            annoView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        }
        
        
        annoView!.pinTintColor = .purple
        annoView!.animatesDrop = true
        
        return annoView
        
        
    }
    
//MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
    let location = locations.last
    
    if let location = location {
        
           //反地理编码
             
         let geoCoder = CLGeocoder.init()
         geoCoder.reverseGeocodeLocation(location) { (placemarks:[CLPlacemark]?, error:Error?) in
            
            if let _ = error {
               return
             }else
             {
                print("no error")
             }
             
             guard let newPlacemarks = placemarks else {
                print("placemarks is nil")
                return
             }
             
                 
             let placemark = newPlacemarks.last
             let locality = placemark?.locality
             let subLocality = placemark?.subLocality
             let name = placemark?.name
                     
            print("locality:",locality)
            print("subLocality:",subLocality)
            print("name:",name)

                    
             }
              
           
        }
    }
    
   
    
}
